package com.worldwind.test;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.R;
import com.location.test.LocationService;
import com.sql.test.activity.AttributeSqlActivity;
import com.sql.test.activity.RemoteAttributeSqlActivity;
import com.sql.test.service.DataFormatService;
import com.sql.test.service.DatabaseService;
import com.sql.test.service.LocalDatabaseSerivce;
import com.sql.test.service.RemoteDatabaseService;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import gov.nasa.worldwind.PickedObject;
import gov.nasa.worldwind.PickedObjectList;
import gov.nasa.worldwind.WorldWind;
import gov.nasa.worldwind.WorldWindow;
import gov.nasa.worldwind.geom.Camera;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.globe.BasicElevationCoverage;
import gov.nasa.worldwind.globe.Globe;
import gov.nasa.worldwind.layer.BackgroundLayer;
import gov.nasa.worldwind.layer.BlueMarbleLandsatLayer;
import gov.nasa.worldwind.layer.Layer;
import gov.nasa.worldwind.layer.LayerList;
import gov.nasa.worldwind.layer.RenderableLayer;
import gov.nasa.worldwind.layer.TiandituCia_cLayer;
import gov.nasa.worldwind.layer.TiandituCva_cLayer;
import gov.nasa.worldwind.layer.TiandituImg_cLayer;
import gov.nasa.worldwind.layer.TiandituVec_cLayer;
import gov.nasa.worldwind.shape.Label;
import gov.nasa.worldwind.shape.Path;
import gov.nasa.worldwind.shape.Placemark;
import gov.nasa.worldwind.shape.Polygon;

/**
 * Created by Lenovo on 2018/5/7.
 */

public class RemoteDigitializeFeatureActivity  extends AppCompatActivity implements  GestureDetector.OnGestureListener,NavigationView.OnNavigationItemSelectedListener{
    /**
     * This protected member allows derived classes to override the resource used in setContentView.
     */

    //part1:导航栏设计
    //选项菜单弹出对话框属性
    protected String aboutBoxTitle = "World Wind Cumpus";        // TODO: use a string resource, e.g., app name

    protected String aboutBoxText = "A controller of layers";    // TODO: make this a string resource
    //工具条中添加图层导航栏

    protected static int selectedItemId ;

    protected ActionBarDrawerToggle drawerToggle;

    protected NavigationView navigationView;


    //part2：数据输入
    //主界面布局资源
    protected int layoutResourceId = R.layout.activity_globe;
    //check to draw or not
    CheckBox checkDraw ;
    //check graphics type
    RadioButton checkPoint,checkPolyline,checkPolygon;
    //gesture detector
    GestureDetectorCompat detectorCompat ;
    //basic support
    RenderableLayer labelsLayer = new RenderableLayer();
    ArrayList<Position> pos = new ArrayList<>();
    Position currentPosition;
    boolean startDraw =false;
    //PlacemarkLayer
    RenderableLayer placemarkLayer = new RenderableLayer();
    //Polyline
    RenderableLayer temPolylineLayer = new RenderableLayer();
    RenderableLayer polylineLayer = new RenderableLayer();

    // Polygon
    RenderableLayer temPolygonLayer = new RenderableLayer();
    RenderableLayer polygonLayer = new RenderableLayer();

    //geometry creator
    GeometryCreator geometryCreator = new GeometryCreator();


    //插入数据的空间数据类型
    String type = null;
    //动态添加的属性编辑框集合
    ArrayList<EditText> attriEditTexts = null;
    //处理id属性的编辑框
    EditText idEditText =null;

    //part3:operate database,操作数据库
    //control view,进行交互控制的控件,选择存储表或创建表
    EditText insertTableEditText = null;
    ListView insertTablesListView = null;
    Button btnCreateTable = null;
    //记录所有表名
    ArrayList<String> insertTables = null;
    //当前要插入数据的表
    String insertingTable = null;
    //当前表的属性字段
    ArrayList<String> insertingTableColumns = null;
    //当前表的空间属性字段
    String geometryColumn = null;
    //当前属性表可能存在的id字段,需要查询记录数自动++，或者直接不作为插入字段
    ArrayList<String> idColumn = null;
    //用户输入的数据
    ArrayList<String> inputFeatureData = null;

    //part4：用户设定的自定义空间表的表名，属性及类型,空间字段类型,空间字段名默认为geom，空间维度默认为XY二维，坐标系srid为4326
    String customTableName = null;
    ArrayList<String[]> inputTableInfo = null;
    String customGeometryType = null;

    //调用数据库服务类,进行数据库信息查询及数据插入
    /* //基于本地服务
    LocalDatabaseSerivce localDatabaseSerivce = new LocalDatabaseSerivce();*/
    //基于远程服务
    RemoteDatabaseService remoteDatabaseService = new RemoteDatabaseService();
    //实际使用的服务
    DatabaseService databaseSerivce  = remoteDatabaseService;


    //用于空间数据的文本与坐标格式转换
    DataFormatService dataFormatService = new DataFormatService();


    //记录与查询视图转换
    Button btnToggleSearch = null;

    //进行定位的服务
    LocationService locationService =null;
    RenderableLayer locationLayer = null;


    /**进行线程消息处理，获取子线程传来的数据**/
    //用于判断操作类型
    final int SELECT_CONDITION =0;
    final int SELECT_KEYWORD =1;
    final int SELECT_TABLE=2;
    final int SELECT_COLUMN=3;
    final int SELECT_VALUE =4;
    final int SELECT_CREATE =5;
    final  int SELECT_NUMBER=6;
    final  int INSERT_DATA = 7;
    final int SET_ID = 8;
    //用于与子线程通信，获取数据
    Handler handler =new Handler(){
        public void handleMessage(Message msg){

            //如果返现msg.what，则进行制定操作，如想进行其他操作，则在子线程里将SHOW_RESPONSE改变
            switch (msg.what){
                case SELECT_KEYWORD:

                    break;
                case SELECT_CONDITION:

                    //进行UI操作，将结果显示到界面上
                    break;
                case SELECT_TABLE:
                    ListAdapter listAdapter = new ArrayAdapter<>(getApplicationContext(),R.layout.attribute_item,insertTables);
                    insertTablesListView.setAdapter(listAdapter);
                    insertTablesListView.setVisibility(View.VISIBLE);
                    break;
                case SELECT_COLUMN:
                    insertTablesListView.setVisibility(View.INVISIBLE);
                    break;
                case SELECT_VALUE:

                    break;
                case SELECT_CREATE:
                    //提示信息
                    boolean createSuccess =(boolean) msg.obj;
                    if(createSuccess){
                        Toast.makeText(getApplicationContext(),"创建表成功！",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(),"创建表失败！",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case SELECT_NUMBER:

                    break;
                case INSERT_DATA:
                    boolean insertSuccess = (boolean)msg.obj;
                    if(insertSuccess){
                        switch (type) {
                            case "POINT":
                                //绘制placemark
                                //first attribute is name which used to identify icon,second is desc of poi:第一个属性是名称，第二属性是描述
                                Placemark placemark = geometryCreator.createPlacemark(currentPosition, attriEditTexts.get(0).getText().toString());
                                Label placemarklabel = geometryCreator.createLabel(currentPosition,attriEditTexts.get(1).getText().toString());
                                //记录除空间属性之外的属性数据到要素对象
                                for (int i = 0; i < insertingTableColumns.size(); i++) {
                                    placemark.putUserProperty(insertingTableColumns.get(i), inputFeatureData.get(i));
                                }
                                placemarkLayer.addRenderable(placemark);
                                labelsLayer.addRenderable(placemarklabel);
                                break;
                            case "POLYLINE":
                                Path polyline = geometryCreator.createPolyline(pos);
                                //记录除空间属性之外的属性数据到要素对象
                                for (int i = 0; i < insertingTableColumns.size(); i++) {
                                    polyline.putUserProperty(insertingTableColumns.get(i), inputFeatureData.get(i));
                                }
                                placemarkLayer.addRenderable(polyline);
                                break;
                            case "POLYGON":
                                Polygon polygon = geometryCreator.createPolygon(pos);
                                //记录除空间属性之外的属性数据到要素对象
                                for (int i = 0; i < insertingTableColumns.size(); i++) {
                                    polygon.putUserProperty(insertingTableColumns.get(i), inputFeatureData.get(i));
                                }
                                placemarkLayer.addRenderable(polygon);
                                break;
                        }
                        wwd.requestRedraw();

                        Toast.makeText(getApplicationContext(),"数据入库成功！",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(),"数据入库失败！",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case SET_ID:
                    int id = (int)msg.obj;
                    idEditText.setText(String.valueOf(id));
                    break;
            }
        }
    };


    //
    /**
     * The WorldWindow (GLSurfaceView) maintained by this activity
     */
    protected WorldWindow wwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Establish the activity content
        setContentView(this.layoutResourceId);
        this.setTitle("数字化要素（远程）");
        detectorCompat = new GestureDetectorCompat(this,this);
        checkDraw = (CheckBox)findViewById(R.id.checkDraw);
        checkPoint = (RadioButton)findViewById(R.id.point);
        checkPolyline = (RadioButton)findViewById(R.id.polyline);
        checkPolygon = (RadioButton)findViewById(R.id.polygon);
        checkDraw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    wwd.setLongClickable(true);
                    wwd.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            return detectorCompat.onTouchEvent(event);
                        }
                    });
                }else{
                    wwd.setLongClickable(false);
                    wwd.setOnTouchListener(null);
                }
            }
        });

        //database control view
        insertTableEditText =  (EditText) findViewById(R.id.insertTableEdit);
        insertTablesListView = (ListView) findViewById(R.id.insertTablesList);
        btnCreateTable = (Button)findViewById(R.id.btnCreateTable);
        // toggle input to search activity
        btnToggleSearch = (Button)findViewById(R.id.toggleSearch);

        // Create the World Window (a GLSurfaceView) which displays the globe.
        this.wwd = new WorldWindow(this);



        // Override the World Window's built-in navigatior behavior by adding picking support.
        this.wwd.setWorldWindowController(new PickObjectController(this));
        // Add the WorldWindow view object to the layout that was reserved for the globe.
        FrameLayout globeLayout = (FrameLayout) findViewById(R.id.globe);
        globeLayout.addView(this.wwd);

        // Setup the World Window's layers.
        this.wwd.getLayers().addLayer(new BackgroundLayer());
        this.wwd.getLayers().addLayer(new BlueMarbleLandsatLayer());

        // Setup the World Window's elevation coverages.
        this.wwd.getGlobe().getElevationModel().addCoverage(new BasicElevationCoverage());
        //add init map service
        Layer layer = new TiandituImg_cLayer();
        layer.setDisplayName(getText(R.string.tiandituImgLayerName).toString());
        this.wwd.getLayers().addLayer(layer);
        //add feature layer
        this.wwd.getLayers().addLayer(placemarkLayer);
        this.wwd.getLayers().addLayer(temPolylineLayer);
        this.wwd.getLayers().addLayer(polylineLayer);
        this.wwd.getLayers().addLayer(temPolygonLayer);
        this.wwd.getLayers().addLayer(polygonLayer);
        this.wwd.getLayers().addLayer(labelsLayer);
        // copy database file
        databaseSerivce.loadLocalDB(this);

        //添加导航栏
        onCreateDrawer();

        //用于切换学校区域和全球显示视图
        FloatingActionButton codeViewButton = (FloatingActionButton) findViewById(R.id.fab);
        codeViewButton.setVisibility(View.VISIBLE);    // is set to GONE in layout
        codeViewButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //判断当前是区域显示还是全球显示
                if (wwd.getNavigator().getAltitude()>10e4){
                    //如果是全球显示，转换到学校区域视图
                    Globe globe = getWorldWindow().getGlobe();
                    Camera camera = new Camera();
                    camera.set(35.94, 120.17, 2500, WorldWind.ABSOLUTE, 0, 0, 0.0 /*roll*/);
                    getWorldWindow().getNavigator().setAsCamera(globe, camera);
                    wwd.requestRedraw();
                }else{
                    // 如果是区域显示，转换到全球视图
                    Globe globe = getWorldWindow().getGlobe();
                    Camera camera = new Camera();
                    camera.set(35.94, 120.17, 10e6, WorldWind.ABSOLUTE, 0, 0, 0.0 /*roll*/);
                    getWorldWindow().getNavigator().setAsCamera(globe, camera);
                    wwd.requestRedraw();
                }
            }
        });

        //定位服务
        locationLayer = new RenderableLayer();
        wwd.getLayers().addLayer(locationLayer);
        locationService= new LocationService(this,wwd,locationLayer);
        locationService.startLocation();

    }


    @Override
    protected void onStart() {
        super.onStart();
        //add database control view listener
        insertTableEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击后获取数据库表清单,并生成列表供选择
                //tables
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            insertTables = databaseSerivce.selectTablesName(getApplicationContext());
                            Message message = new Message();
                            message.what = SELECT_TABLE;
                            handler.sendMessage(message);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }).start();

            }
        });
        insertTablesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                insertingTable = insertTablesListView.getItemAtPosition(position).toString();
                insertTableEditText.setText(insertingTable);
                //根据选中的表，查询其属性字段,insertingTableColumns不包含geometryColumn，但包含idColumn，如果有的话
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            insertingTableColumns = databaseSerivce.selectCoulmnsName(getApplicationContext(), insertingTable);
                            geometryColumn = databaseSerivce.getGeometryColumn();
                            Message message = new Message();
                            message.what = SELECT_COLUMN;
                            handler.sendMessage(message);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                //选中一项后隐藏列表
              }
        });
        //to create table:创建表
        btnCreateTable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出自定义表设置对话框
                createTableDialog();
            }
        });

        btnToggleSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), RemoteAttributeSqlActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        this.wwd.onPause(); // pauses the rendering thread
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.navigationView.setCheckedItem(selectedItemId);
        this.wwd.onResume(); // resumes a paused rendering thread
    }


    //添加工具条中的选项菜单，about
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //选项菜单
        this.getMenuInflater().inflate(R.menu.about_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //如果点击了选项菜单，将显示相应的选项信息
        int id = item.getItemId();
        if (id == R.id.action_about) {
            showAboutBox();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    /**
     * This method is invoked when the About button is selected in the Options menu.
     */
    protected void showAboutBox() {
        //选项菜单被点击后，显示简单信息提示对话框
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle(this.aboutBoxTitle);
        alertDialogBuilder
                .setMessage(this.aboutBoxText)
                .setCancelable(true)
                .setNegativeButton("Close", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }




    public WorldWindow getWorldWindow() {
        return this.wwd;
    }

    @Override
    public boolean onDown(MotionEvent e) {

        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        //清空之前的点数据，进行新要素绘制
        if(!startDraw) {
            pos.clear();
            startDraw = true;
        }
        if (checkPoint.isChecked()) {
            //绘制点
            currentPosition = this.getCurrentPosition(e);
            pos.add(currentPosition);
            type = "POINT" ;
            inputAttriDialog(type);
            startDraw =false;
        } else if (checkPolyline.isChecked()) {
            //绘制线
            currentPosition = this.getCurrentPosition(e);
            pos.add(currentPosition);
            if (pos.size() > 1) {
                //清空临时图层旧要素，并添加新要素
                temPolylineLayer.clearRenderables();
                temPolylineLayer.addRenderable(geometryCreator.createPolyline(pos));
                wwd.requestRedraw();
            }
        } else if (checkPolygon.isChecked()) {
            //绘制面
            currentPosition = this.getCurrentPosition(e);
            pos.add(currentPosition);
            if (pos.size() > 2) {
                //清空临时图层旧要素，并添加新要素
                temPolygonLayer.clearRenderables();
                temPolygonLayer.addRenderable(geometryCreator.createPolygon(pos));
                wwd.requestRedraw();
            }
        }
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }


    @Override
    public void onLongPress(MotionEvent e) {

        if(checkPolyline.isChecked()){
            //结束线要素的绘制，输入要素属性，并绘制要素到结果图层polylineLayer，最后清空临时图层
            currentPosition = this.getCurrentPosition(e);
            pos.add(currentPosition);
            type = "POLYLINE" ;
            inputAttriDialog(type);
            //clear temp layer:清空临时图层
            temPolylineLayer.clearRenderables();
        }else if(checkPolygon.isChecked()){
            //结束面要素的绘制，输入要素属性，并绘制要素到结果图层polylineLayer，最后清空临时图层
            currentPosition = this.getCurrentPosition(e);
            pos.add(currentPosition);
            type = "POLYGON" ;
            inputAttriDialog(type);
            //clear temp layer:清空临时图层
            temPolygonLayer.clearRenderables();
        }
        //本图形绘制结束，准备绘制新图形
        startDraw = false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }




    public Position getCurrentPosition(MotionEvent event) {
        // Forget our last picked object
        // Perform a new pick at the screen x, y
        PickedObjectList pickList = getWorldWindow().pick(event.getX(), event.getY());

        // Get the top-most object for our new picked object
        PickedObject top = pickList.topPickedObject();
        Position p = null;
        if (top != null) {
            if (top != null&&top.isTerrain()) {
                p = top.getTerrainPosition();
            }
        }
        return p;
    }


    public void inputAttriDialog(final String type){

        final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
        final int MP = ViewGroup.LayoutParams.MATCH_PARENT;
        TableLayout attributeFrom = (TableLayout)getLayoutInflater().inflate(R.layout.feature_attribute,null);
        //code generate views
        /**
         *     <TableRow>
         <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="要素名："
         android:textSize="10pt"/>
         <EditText
         android:id="@+id/featureName"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:hint="请填写要素名称"
         android:selectAllOnFocus="true"/>
         </TableRow>
         * */
        //用于保存代码创建的EditText控件，以便按顺序获取输入值
        attriEditTexts = new ArrayList<>();

        for(int i =0;i<insertingTableColumns.size();i++) {

            //判断是否为id字段
            String regEx="id$|ID$|Id$"; //表示以id或ID结尾的字符串
            Pattern p=Pattern.compile(regEx);
            Matcher m=p.matcher(insertingTableColumns.get(i));
            boolean result=m.find();

            //
            TableRow tableRow = new TableRow(this);
            TextView textView = new TextView(this);
            EditText editText = new EditText(this);
            textView.setText(insertingTableColumns.get(i)+"：");
            textView.setTextSize(20);
            textView.setVisibility(View.VISIBLE);
            if(result){
                //一般，id号从0开始
                //用于保存id编辑框，以便获取id数据后对其操作
                idEditText = editText;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int id  = databaseSerivce.getRecordsNumber(getApplicationContext(),insertingTable);
                        Message message = new Message();
                        message.what = SET_ID;
                        message.obj = id;
                        handler.sendMessage(message);
                    }
                }).start();

            }else {
                editText.setHint("请输入" + insertingTableColumns.get(i));
                editText.setSelectAllOnFocus(true);
            }
            editText.setVisibility(View.VISIBLE);
            //android:layout_width="wrap_content" //android:layout_height="wrap_content"
            TableLayout.LayoutParams layoutParams = new TableLayout.LayoutParams(MP,WC);
            tableRow.addView(textView);
            tableRow.addView(editText);
            tableRow.setVisibility(View.VISIBLE);
            attributeFrom.addView(tableRow,layoutParams);

            attriEditTexts.add(editText);
        }

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置属性")
                .setView(attributeFrom)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Toast.makeText(getApplicationContext(),"单击了［确定］按钮",Toast.LENGTH_SHORT).show();
                        //空间及属性数据存入数据库
                        inputFeatureData = new ArrayList<>();
                        for(int i=0;i<insertingTableColumns.size();i++){
                            inputFeatureData.add(attriEditTexts.get(i).getText().toString());
                        }
                        //进行空间数据格式转换
                        String geometryText = dataFormatService.geometryToText(pos,type);
                        inputFeatureData.add(geometryText);
                      /*  //如果表设置了触发器，会造成插入失败，先删除表中触发器，再插入
                        boolean deleteTriggerSuccess = databaseSerivce.dropAllTrigger(getApplicationContext(),insertingTable);
                       */
                        //调用数据库服务进行数据插入
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                boolean insertSuccess = databaseSerivce.insertFeatureData(getApplicationContext(),insertingTable,insertingTableColumns,inputFeatureData,geometryColumn);
                                Message message = new Message();
                                message.what = INSERT_DATA;
                                message.obj = insertSuccess;
                                handler.sendMessage(message);
                            }
                        }).start();

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        wwd.requestRedraw();
                        Toast.makeText(getApplicationContext(),"单击了［取消］按钮",Toast.LENGTH_SHORT).show();

                    }
                })
                .create()
                .show();
    }

    public void createTableDialog(){
        final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
        final int MP = ViewGroup.LayoutParams.MATCH_PARENT;
        final LinearLayout tableInfoFrom = (LinearLayout)getLayoutInflater().inflate(R.layout.table_info,null);
        //用于添加属性的按钮
        Button btnAddColumn = (Button)tableInfoFrom.findViewById(R.id.btnAddColumn);
        //表名和空间类型的输入控件
        final EditText tableNameEdit = (EditText)tableInfoFrom.findViewById(R.id.tableNameEdit);
        final EditText geometryTypeEdit = (EditText)tableInfoFrom.findViewById(R.id.geometryType);

        //code generate views
        //用于保存代码创建的EditText控件，以便按顺序获取输入值
        final ArrayList<EditText[]> columnEditTexts = new ArrayList<>();
        //添加一般属性
        btnAddColumn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加属性输入控件
                TableLayout tableLayout = (TableLayout)tableInfoFrom.findViewById(R.id.tableInfoLayout);
                TableRow tableRow = new TableRow(getApplicationContext());
                EditText columnNameEditText = (EditText) getLayoutInflater().inflate(R.layout.tableinfo_editview,null);//new EditText(getApplicationContext());
                EditText columnTypeeditText = (EditText) getLayoutInflater().inflate(R.layout.tableinfo_editview,null);
                //获取属性名的文本框
                columnNameEditText.setHint("属性名");
                columnNameEditText.setSelectAllOnFocus(true);
                //设置字体颜色，默认白色与背景同色，无法看见
                columnNameEditText.setTextColor(android.graphics.Color.BLACK);
                //设置光标可见,但是问题依旧，看来EditText得通过xml解析得到而不能new了
                columnNameEditText.setCursorVisible(true);
                columnNameEditText.setVisibility(View.VISIBLE);

                //获取属性类型的文本框
                columnTypeeditText.setHint("INTEGER/REAL/TEXT");
                columnTypeeditText.setSelectAllOnFocus(true);
                //设置字体颜色，默认白色与背景同色，无法看见
                columnTypeeditText.setTextColor(android.graphics.Color.BLACK);
                //设置光标可见
                columnTypeeditText.setCursorVisible(true);
                columnTypeeditText.setVisibility(View.VISIBLE);

                //android:layout_width="wrap_content" //android:layout_height="wrap_content"
                TableLayout.LayoutParams layoutParams = new TableLayout.LayoutParams(MP,WC);
                tableRow.addView(columnNameEditText);
                tableRow.addView(columnTypeeditText);
                tableRow.setVisibility(View.VISIBLE);
                tableLayout.addView(tableRow,layoutParams);
                //存储控件对象，以便随后获取输入值，创建表
                EditText[] name_type = new EditText[2];
                name_type[0] = columnNameEditText;
                name_type[1] = columnTypeeditText;
                columnEditTexts.add(name_type);
            }
        });


        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置属性")
                .setView(tableInfoFrom)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"单击了［确定］按钮",Toast.LENGTH_SHORT).show();
                        //获取输入信息，调用数据库服务创建表
                        inputTableInfo = new ArrayList<>();
                        for(int i=0;i<columnEditTexts.size();i++){
                            //属性信息：属性名和属性类型
                            String [] columnInfo= new String[2];
                            //属性名
                            columnInfo[0] = columnEditTexts.get(i)[0].getText().toString();
                            //属性数据类型
                            columnInfo[1] = columnEditTexts.get(i)[1].getText().toString();
                            inputTableInfo.add(columnInfo);
                        }
                        //获取表名
                        customTableName = tableNameEdit.getText().toString();
                        //获取空间数据类型
                        customGeometryType =geometryTypeEdit.getText().toString();
                        //开辟子线程，发送创建表请求
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                boolean createSuccess = databaseSerivce.createTable(getApplicationContext(),customTableName,customGeometryType,inputTableInfo);
                                Message message = new Message();
                                message.what = SELECT_CREATE;
                                message.obj = createSuccess;
                                handler.sendMessage(message);
                            }
                        }).start();


                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"单击了［取消］按钮",Toast.LENGTH_SHORT).show();
                    }
                })
                .create()
                .show();
    }


    //导航监听及方法
    protected void onCreateDrawer() {
        // Add support for a Toolbar and set to act as the ActionBar
        Toolbar toolbar = (Toolbar) this.findViewById(R.id.toolbar);
        /*此处抛出该异常： if (ab instanceof WindowDecorActionBar) {
        throw new IllegalStateException("This Activity already has an action bar supplied " +
                "by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set " +
                 "windowActionBar to false in your theme to use a Toolbar instead.");
        }*/
        //解决方案：设置toolbar的theme,添加style theme资源
        // android:theme="@style/AppTheme.PopupOverlay"
        //关键在于设置Manifest.xml中，设置activity的theme>>android:theme="@style/AppTheme.NoActionBar">
        this.setSupportActionBar(toolbar);

        // Add support for the navigation drawer full of examples
        //The DrawerLayout to link to the given Activity's ActionBar
        DrawerLayout drawer = (DrawerLayout) this.findViewById(R.id.drawer_layout);

        this.drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(this.drawerToggle);
        this.drawerToggle.syncState();
        //添加导航栏监听
        this.navigationView = (NavigationView) this.findViewById(R.id.nav_view);
        this.navigationView.setNavigationItemSelectedListener(this);
        this.navigationView.setCheckedItem(selectedItemId);
    }



    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Persist the selected item between Activities
        selectedItemId = item.getItemId();

        // Handle navigation view item clicks here.
        switch (selectedItemId) {
            case R.id.TiandituVecLayer:
                //需要允许网络访问，设置manifest中的网络权限，否则无法加载在线服务
                loadLayer(new TiandituVec_cLayer(),R.string.tiandituVecLayerName);
                break;
            case R.id.TiandituImgLayer:
                loadLayer(new TiandituImg_cLayer(), R.string.tiandituImgLayerName);
                break;
            case R.id.TiandituCvaLayer:
                loadLayer(new TiandituCva_cLayer(), R.string.tiandituCvaLayerName);
                break;
            case R.id.TiandituCiaLayer:
                loadLayer(new TiandituCia_cLayer(), R.string.tiandituCiaLayerName);
                break;

        }
        //自动隐藏
        DrawerLayout drawer = (DrawerLayout) this.findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }



    public void  loadLayer(Layer layer, int layerName){
        this.setTitle(layerName);
        layer.setDisplayName(this.getText(layerName).toString());
        //根据图层名删除已经加载的图层，避免重复加载,
        LayerList layerList = this.wwd.getLayers();
        Iterator<Layer> iterator = layerList.iterator();
        Layer previousLayer = null;
        while (iterator.hasNext()){
            Layer currentlayer = iterator.next();
            if(currentlayer.getDisplayName()!=null) {
                if (currentlayer.getDisplayName().equals(this.getText(layerName).toString())) {
                    previousLayer = currentlayer;
                }
            }
        }
        //如果图层已存在，删除后加载到当前顶层
        if(previousLayer!=null) {
            this.wwd.getLayers().removeLayer(previousLayer);
        }
        //加载图层
        this.wwd.getLayers().addLayer(layer);
        //重绘
        this.wwd.requestRedraw();

    }

}
